package com.xb.loan.cashier.biz.service.impl;

import com.xb.loan.cashier.biz.dao.bean.CashierPayChannel;
import com.xb.loan.cashier.biz.pay.bankcomm.BankcommConst;
import com.xb.loan.cashier.biz.pay.bankcomm.BankcommPayment;
import com.xb.loan.cashier.biz.service.CashierPayChannelService;
import com.xb.loan.cashier.biz.util.Configure;
import com.xb.loan.cashier.service.IRealAuthService;
import com.xb.loan.cashier.service.bean.RealAuthBO;
import com.xb.loan.cashier.service.constant.ICashierEnumConst;
import com.xb.loan.cashier.service.exception.ICashierServiceException;
import com.xb.loan.encryptor.crypt.Encryptor;
import com.xb.loan.encryptor.crypt.EncryptorManager;
import com.xb.loan.log.exception.BizException;
import com.xb.loan.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service("realAuthService")
public class RealAuthServiceImpl implements IRealAuthService {

	private static final Logger log = LoggerFactory.getLogger(RealAuthServiceImpl.class);
    
    @Autowired
    private CashierPayChannelService cashierPayChannelService;
    
	/**
	 * 获取channelId
	 * @param platId
	 * @param payChannelType
	 * @param payType
	 * @return
	 * @throws BizException
	 * @author zljun
	 * @date 2016年9月23日
	 */
	private CashierPayChannel getPayChannel(String platId, int payChannelType, int payType) throws BizException {
    	log.info("getPayChannel platId="+platId+",payChannelType="+payChannelType+",payType="+payType);
    	// 根据平台id查询所有可用充值支付渠道
    	List<CashierPayChannel> channelList = cashierPayChannelService.queryListByPlatId(platId, payType);
    	if(channelList != null && channelList.size() > 0) {
    		for(CashierPayChannel channel : channelList) {
    			if(channel.getPaychannelType() == payChannelType) {
    				return channel;
    			}
    		}
    	}
    	throw ICashierServiceException.PAY_CHANNEL_NOT_EXIST;
    }

	
	/**
	 * 参数验证
	 * @param realAuthBO
	 * @throws BizException
	 * @author zljun
	 * @date 2016年9月23日
	 */
	private void paramsVerify(RealAuthBO realAuthBO) throws BizException{
		//15居民身份证;16临时身份证;17军人身份证件;18武警身份证件;19港澳台居民通行证;20护照;21其他;22临时户口;23户口簿;24边境证
		List<String> certTypeList = Arrays.asList(new String[]{null,"","15","16","17","18","19","20","21","22","23","24"});
		if (!certTypeList.contains(realAuthBO.getCertType())) {
			throw ICashierServiceException.CERT_TYPE_ERROR;
		}
		if (realAuthBO.getPayChannelType()==0) {
			throw ICashierServiceException.PAY_CHANNEL_TYPE_ERROR;
		}
		if(realAuthBO.getPayType()<0 || realAuthBO.getPayType()>1) {
    		throw ICashierServiceException.PAY_TYPE_ERROR;
    	}
    	if(StringUtils.isEmpty(realAuthBO.getPlatId())) {
    		throw ICashierServiceException.PLAT_ID_IS_NULL;
    	}
    	if(StringUtils.isEmpty(realAuthBO.getCardNo())) {
    		throw ICashierServiceException.CARDNO_IS_NULL;
    	}
    	if(StringUtils.isEmpty(realAuthBO.getCustName())) {
    		throw ICashierServiceException.CUSTNAME_IS_NULL;
    	}
    	if(StringUtils.isEmpty(realAuthBO.getSign())) {
    		throw ICashierServiceException.SIGN_IS_NULL;
    	}
	}
	
	/**
	 * 验签
	 * @param realAuthBO
	 * @return
	 * @author zljun
	 * @date 2016年9月23日
	 */
	private boolean signVerify(RealAuthBO realAuthBO){
		Encryptor encrytor = EncryptorManager.getEncryptor("partner");
        StringBuffer msg = new StringBuffer();
        String split = ICashierEnumConst.EncryptStrCentor.COMMON.getCode();
        msg.append(realAuthBO.getPayChannelType()).append(split);
        msg.append(realAuthBO.getTradeType()).append(split);
        msg.append(realAuthBO.getPayType()).append(split);
        msg.append(realAuthBO.getPlatId()).append(split);
        msg.append(realAuthBO.getCardNo()).append(split);
        msg.append(realAuthBO.getCustName()).append(split);
        msg.append(realAuthBO.getCertType()).append(split);
        msg.append(realAuthBO.getCertNo());
        // 加密数据校验
        String encryptId = Configure.getStringValue("encrypt.cashier.id");
        
		return encrytor.encryptValidate(encryptId, null, msg.toString(), realAuthBO.getSign());
	}
	
	@Override
	public void realAuth(RealAuthBO realAuthBO) throws BizException {
		log.info("realAuth "+realAuthBO.toString());
		paramsVerify(realAuthBO);
		if(!signVerify(realAuthBO)) {
        	throw ICashierServiceException.VALIDATE_ERROR;
        }
		CashierPayChannel payChannel = this.getPayChannel(realAuthBO.getPlatId(), realAuthBO.getPayChannelType(), realAuthBO.getPayType());
		Map<String, Object> xmlResMap = BankcommPayment.realAuth(
				payChannel.getQueryUrl(), payChannel.getChannelUser(), realAuthBO.getCardNo(),
				realAuthBO.getCustName(), realAuthBO.getCertType(), realAuthBO.getCertNo());
		if (xmlResMap==null) {
        	log.info("realAuth xmlResMap is null");
			throw ICashierServiceException.systemException;
		}
		Map<String, String> headResMap = (Map<String, String>)xmlResMap.get(BankcommConst.HEAD);
		String rspType = headResMap.get(BankcommConst.RSP_TYPE);
		if (BankcommConst.FAIL.equals(rspType)) {
			String rspCode = headResMap.get(BankcommConst.RSP_CODE);
			String rspMsg = headResMap.get(BankcommConst.RSP_MSG);
			log.info("realAuth 实名认证异常   rspType="+rspType+",rspCode="+rspCode+",rspMsg="+rspMsg);
			throw ICashierServiceException.systemException;
		}
	}
	
}
